package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper usersMapper;
    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        //计算出两头之间中间的日期，访日到List<LocalDate>
        List<LocalDate> dates = new ArrayList<>();
        //通过循环来计算出中间日期
        while (!begin.isAfter(end)) { //小于结束日期
            dates.add(begin);
            begin = begin.plusDays(1); //日期加1
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            //计算当前开始时间
            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);//获取当前时间的00:00:00
//计算当前结束时间
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);//获取当前时间的23:59:59
            Integer completed = Orders.COMPLETED;
            Map map = new HashMap<>();
            map.put("begin",localDateTime);
            map.put("end",localDateTime1);
            map.put("status",completed);

            Double turnover = ordersMapper.getturnoverStatistics(map);

            turnoverList.add(turnover != null ? turnover : 0.0);
        }
        log.info("营业额数据：{}",turnoverList);

        return  TurnoverReportVO
                .builder()
                .dateList(String.join(",", dates.stream().map(LocalDate::toString).collect(Collectors.toList()))) //创建一个字符串，以逗号分割
                .turnoverList(String.join(",", turnoverList.stream().map(String::valueOf).collect(Collectors.toList())))
                .build();


    }
    /**
     * 用户统计
     * */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dates.add(begin);
            begin = begin.plusDays(1);//日期加1
        }
        //新增用户列表
        List<Integer> newUserList = new ArrayList<>();
        //累计用户列表
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dates){
            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);
            newUserList.add(getUserCount(localDateTime,localDateTime1));
            totalUserList.add(getUserCount(null,localDateTime1));

        }
        log.info("用户数据：{}",newUserList);
        return UserReportVO
                .builder()
                .dateList(String.join(",", dates.stream().map(LocalDate::toString).collect(Collectors.toList())))
                .newUserList(String.join(",", newUserList.stream().map(String::valueOf).collect(Collectors.toList())))
                .totalUserList(String.join(",", totalUserList.stream().map(String::valueOf).collect(Collectors.toList())))
                .build();
    }
    /**
     * 订单统计
     * */

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //计算出两头之间中间的日期，访日到List<LocalDate>
        List<LocalDate> dates = new ArrayList<>();
        //通过循环来计算出中间日期
        while (!begin.isAfter(end)) { //小于结束日期
            dates.add(begin);
            begin = begin.plusDays(1); //日期加1
    }
        List<Integer> orderCountList = new ArrayList<>();//记录每天总订单数！
        List<Integer> validOrderCountList = new ArrayList<>();//记录每天有效订单数！
        for (LocalDate date : dates) {
            LocalDateTime localDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime localDateTime1 = LocalDateTime.of(date, LocalTime.MAX);
            Integer completed = Orders.COMPLETED;
            //查询每天的订单数
            Integer orderCount = getOrderCount(localDateTime, localDateTime1, null);
            orderCountList.add(orderCount);
            //查询每天的有效订单数
            Integer validOrderCount = getOrderCount(localDateTime, localDateTime1, completed);
            validOrderCountList.add(validOrderCount);
        }
        //时间区间内的总订单数
        Integer orderCount = orderCountList.stream().reduce(0,Integer::sum);//集合求和
        //时间区间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(0,Integer::sum); //集合求和
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(orderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / orderCount; //有效订单数除以总订单数
        }
        log.info("订单数据：{}",orderCountList);

        return OrderReportVO
                .builder()
                .dateList(String.join(",", dates.stream().map(LocalDate::toString).collect(Collectors.toList())))
                .orderCountList(String.join(",", orderCountList.stream().map(String::valueOf).collect(Collectors.toList())))
                .validOrderCountList(String.join(",", validOrderCountList.stream().map(String::valueOf).collect(Collectors.toList())))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 1. 计算时间区间（整个区间查一次，而非每天查）
        LocalDateTime startTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 2. 假设mapper返回的是销量前10的菜品列表（包含名称和数量）
        // 建议定义DTO：List<SalesTop10DTO>，包含name和number字段
        Map map = new HashMap();
        map.put("begin",startTime);
        map.put("end", endTime);
        List<GoodsSalesDTO> top10List = ordersMapper.getSalesTop10(map);

        // 3. 提取名称和数量列表
        List<String> nameList = top10List.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.toList());
        List<String> numberList = top10List.stream()
                .map(dto -> String.valueOf(dto.getNumber()))
                .collect(Collectors.toList());
        log.info("销量数据：{}",top10List);

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }
    /**
     * 导出营业数据
     * */

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //数据库查询营业数据--最近30天的数据
        //我们在之前的工作台接口已经创建了营业额，新增用户，订单完成率，订单完成数等，所以直接调用！
        //我们查询的是30天的数据，所以需要计算出30天前的日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1) ;
        //我们需要的数据为LocalDateTime，而现在为LocalDate，所以需要转换！
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        //获取日期内的每一天的数据


        //将查询的数据写入到excel中
        //我们是通过模板创建Excel，所以需要先导入一个模板，使用流的方式读取模板
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("D:\\桌面\\项目\\苍穹外卖\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx");
            //基于模板创建一个excel文件
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            //TODO:填充数据,
            // 1.概括数据上方填写时间日期，
            // 2.营业额，
            // 3.新增用户，
            // 4.订单完成率，
            // 5.订单完成数
            //填写数据之前要获取Sheet页
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            //获取第二行
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin + "至" + end);
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获得第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充明细数据：
            for (int i = 0; i < 30; i++) {
                //获得开始日期：
                LocalDate localDate = begin.plusDays(i);//获取下一天
                //调用workspaceService.getBusinessData(beginTime, endTime);来查询数据
                LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
                businessData = workspaceService.getBusinessData(localDateTime, endTime);
                //获得第8行：
                row = sheet.getRow(7 + i);
                //第六行第二列为日期
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(businessData.getTurnover()); //营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount());//有效订单数
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice());//平均单价
                row.getCell(6).setCellValue(businessData.getNewUsers());//新增用户数

            }


            //将excel文件写到客户端
            //通过HttpServletResponse对象获取OutputStream流，将文件输出到客户端
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            System.out.println("导出成功！");
            workbook.close();
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return usersMapper.getUserStatistics(map);
    }
    /**
     * 根据时间区间统计订单数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        map.put("status", status);
        return ordersMapper.getOrderCount(map);
    }
}
